package com.woniuxy.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.controller.info.Result;
import com.woniuxy.controller.info.SimpleAccountnfo;
import com.woniuxy.dao.ResourceDao;
import com.woniuxy.util.ObjectRedisTemplate;
import com.woniuxy.util.WoniuCopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    @Lazy
    private ResourceDao resourceDao;


    private ObjectMapper objectMapper =new ObjectMapper();

    @Autowired
    private ObjectRedisTemplate objectRedisTemplate;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf8");
        response.setCharacterEncoding("utf-8");
        SimpleAccountnfo simpleUserInfo = WoniuCopyUtil.copyOne(authentication.getPrincipal(), SimpleAccountnfo.class);
        List<String> list =resourceDao.getResourceUriList(simpleUserInfo.getAccountId());
        simpleUserInfo.setUris(list);
        request.getSession().setAttribute("LoginUser:info:id","LoginUser:info:id"+simpleUserInfo.getAccountId());
        objectRedisTemplate.opsForValue().setIfAbsent("LoginUser:info:id"+simpleUserInfo.getAccountId(),simpleUserInfo,60*1, TimeUnit.SECONDS);
        response.getWriter().write(objectMapper.writeValueAsString(Result.getInstance(SimpleAccountnfo.class).setData(simpleUserInfo)));

    }
}
